import { inject, observer } from 'mobx-react';
import { Storage } from '@/assets/js/storage';
import { LOGIN_USERINFO } from '@/utils/constant'
import React, { useState, useEffect } from 'react';
import { Modal, Input, message, Button } from "antd";
import { withRouter } from "react-router-dom";
import QRCode  from 'qrcode.react';
import './index.scss';
import {
  bindAccount,
  reset,
  secret,
  checkBind,
} from '@/api/api'
const { confirm } = Modal;
let milCToken = {}

const CheckBind = (props) => {
  const loginUserInfo = Storage.get(LOGIN_USERINFO)
  let [ checkBindShow, setCheckBindShow ] = useState(false);
  let [ isBind , setIsBind] = useState(false);
  let [ secretObj, setSecretObj ] = useState({});
  let code = '';
  
  const getCheckBind = () => {
    try {
      if (typeof milCToken.source === 'function') {
        milCToken.source('终止请求'); //取消请求
      }
  	  checkBind({
        'userAccount': loginUserInfo.account
      }).then((res)=>{
        isBind = res.data;
        setIsBind(res.data);
        if(isBind === false){
          getSecret();
        }else{
          checkBindShow = true;
          setCheckBindShow(true)
        }
  	  })
    } catch (error) {
      console.log(error)
    }
  }
  
  const getSecret = () => {
    try {
      if (typeof milCToken.source === 'function') {
        milCToken.source('终止请求'); //取消请求
      }
  	  secret({
        webSide: '1'
      }).then((res)=>{
        if(res.code === 0){
          secretObj = res.data;
          setSecretObj(res.data);
          
          checkBindShow = true;
          setCheckBindShow(true)
        }
  	  })
    } catch (error) {
      console.log(error)
    }
  }
  
  const bindFn = () => {
    try {
      if (typeof milCToken.source === 'function') {
        milCToken.source('终止请求'); //取消请求
      }
	  if(!code){
		  message.warning('请输入谷歌验证码')
	  }else{
		bindAccount({
		  code: code,
		  secret: secretObj.secret
		}).then((res)=>{
		  if(res.code === 0){
			  setCheckBindShow(false);
			  message.success("绑定成功")
        getCheckBind()
		  }
		})  
	  }
    } catch (error) {
      console.log(error)
    }
  }
  
  const resetFn = () => {
    try {
      if (typeof milCToken.source === 'function') {
        milCToken.source('终止请求'); //取消请求
      }
      confirm({
        content: '确认重置？',
        onOk() {
          reset().then((res)=>{
            if(res.code === 0){
              setCheckBindShow(false);
              message.success("重置成功")
              getCheckBind()
            }
          })
        },
        onCancel() {},
      });
    } catch (error) {
      console.log(error)
    }
  }
  
  const onChange = (e) => {
    code = e.target.value;
  }
  
  // 首次加载
  useEffect(() => {
    getCheckBind()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])
  
  
  return (
    <>
      <div className="CheckBindModal">
        {
          isBind ?
          <div className="CheckBind">
            状态：已绑定 &nbsp;&nbsp;&nbsp;<Button type="primary" onClick={resetFn}>重置</Button>
          </div>
          :
          <div>
            <div className="line">
              <div className="left">步骤：</div>
              <div className="right step">
                1.下载安装Google认证器 （Authenticator）客户端。目前客户端有:android版|ios版。<br />
                2.然后选择“扫描条形码”。
              </div>
            </div>
            <div className="line">
              <div className="left">二维码：</div>
              <div className="right">
                <div className="step">3.扫描以下二维码，再输入下方二次验证码完成认证。</div>
                <div className="qrcode">
                  {
                    secretObj && secretObj.qrCode
                    ?
                    <QRCode
                      value={secretObj.qrCode}
                      size={200}
                      fgColor="#000000"
                    />
                    :
                    ''
                  }
                  <div>{secretObj.secret}</div>
                </div>
              </div>
            </div>
            <div className="line">
              <div className="left">二次验证码：</div>
              <div className="right">
                <Input style={{width: '150px'}} placeholder="请输入谷歌验证码" onChange={onChange} maxLength={10} />
              </div>
            </div>
          </div>
        }
        <div className="btn">
          <Button type="primary" onClick={()=>{ isBind ? setCheckBindShow(false) : bindFn()}}>确定</Button>
        </div>
      </div>
    </>
  );
};

export default withRouter(inject('store')(observer(CheckBind)));
